<template>
  <div class=""></div>
</template>

<script setup lang="ts">
  function ajaxRequest(url, method, data, callback) {
    // 创建 XMLHttpRequest 对象
    const xhr = new XMLHttpRequest()
    // 发送请求
    xhr.open(method, url, true)
    // 注册回调函数，当请求完成时调用
    xhr.onload = function () {
      if (xhr.status === 200) {
        const response = JSON.parse(xhr.responseText)
        callback(null, response)
      } else {
        callback('请求失败：' + xhr.status, null)
      }
    }
    xhr.onerror = function () {
      callback('请求错误', null)
    }
    xhr.send(data)
  }

  //   使用
  var data = {
    name: 'John',
    age: 25
  }

  function callback(response: any) {
    console.log(response)
  }

  ajaxRequest('http://example.com/api', 'POST', data, callback)
</script>

<style lang="less" scoped></style>
